package com.cloud.bssp.netty.protocol.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpServerCodec;

import java.nio.charset.StandardCharsets;

import static org.apache.http.HttpHeaders.CONTENT_LENGTH;

/**
 * @description： TODO
 * @author：weirx
 * @date：2021/11/16 10:41
 * @version：3.0
 */
public class HttpProtocolServer {

    public static void main(String[] args) {
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            ChannelFuture channelFuture = new ServerBootstrap()
                    .group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel nioSocketChannel) {
                            nioSocketChannel.pipeline().addLast(new HttpServerCodec());
                            nioSocketChannel.pipeline().addLast(new SimpleChannelInboundHandler<HttpRequest>() {
                                @Override
                                protected void channelRead0(ChannelHandlerContext channelHandlerContext, HttpRequest httpRequest) {
                                    System.out.println(httpRequest.uri());

                                    //创建响应
                                    DefaultFullHttpResponse response =
                                            new DefaultFullHttpResponse(httpRequest.protocolVersion(), HttpResponseStatus.OK);

                                    byte[] bytes = "<h1>Hello World!<h1>".getBytes(StandardCharsets.UTF_8);
                                    //添加响应内容长度，否则会浏览器会一直处于加载状态
                                    response.headers().setInt(CONTENT_LENGTH, bytes.length);
                                    //添加响应内容
                                    response.content().writeBytes(bytes);

                                    //写入响应
                                    channelHandlerContext.channel().writeAndFlush(response);
                                }
                            });
//
//                            nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter() {
//                                @Override
//                                public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//                                    System.out.println(msg);
//                                    System.out.println("****************");
//                                    System.out.println(msg.getClass());
//
//                                    if (msg instanceof HttpRequest) {
//                                        // TODO do something...
//                                    } else if (msg instanceof HttpContent) {
//                                        // TODO do something...
//                                    }
//                                    super.channelRead(ctx, msg);
//                                }
//                            });
                        }
                    }).bind(8080);
            channelFuture.sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }
}
